/**
 * axios 封装
 * @author 谭邻宣
 * @date 2020/7/10 16:24
 **/
import axios from 'axios'
// 获取状态

import { DecryptHash, DecryptHashData } from './hashResponse'
import { useUserTokenStore } from '@hook/store'

const HTTP = axios.create({
    timeout: 10 * 1000, //10s 超时
    headers: {
        get: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        post: {
            'Content-Type': 'application/json;charset=utf-8'
        },
    }
})

const whiteApi = [
    ''
]

HTTP.interceptors.request.use(config => {
        const { token } = useUserTokenStore()
        if(token){
            config.headers["Token"] = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

HTTP.interceptors.response.use(response => {
        const { headers , data} = response
        const { VITE_IS_ENCRYPTION } = window.processEnv
        let responseData = data
        // 如果开启了加密 ， 需对返回结果进行解密操作
        if(JSON.parse(VITE_IS_ENCRYPTION)){
            // 获取加密秘钥字符串
            const  serialNumber = headers.get('serialNumber')
            let key = DecryptHash(serialNumber);
            responseData = JSON.parse( DecryptHashData(data, key));
        }

        const { Code } = responseData
        if(Code === 100){
            return responseData
        }else {
            if(Code === -100){

                // 自定义封装消息 ， 关闭后回调
                // $message.error( responseData.Message,()=>{
                //     $router.push({path:'/login'})
                // })

                $message.error( responseData.Message)
                return responseData

            }else{
                $message.error( responseData.Message)
                return responseData
            }
        }

    },
    error => {
    const { message , code , config } =  error
         let key =  config.url.replace(/\//g, '_')
        // 生成一个计数器
        if(!window[key]){
            window[key] = 0
        }
        // 接口502 ， 当前接口重试3次 ， 当计数器大于3 ， 则停止
        if( message.indexOf('502') > 0 && window[key] < 3 ){
            window[key]++;
            const backoff = new Promise(resolve => {
                setTimeout(() => {
                    resolve();
                }, 1000 * window[key]); // 增加每次重试之间的时间间隔
            });
            return backoff.then(() => HTTP.request(config));
        }
        // 不重试后，清除计数器
        delete window[key]

        // // 返回错误消息
        // $message.error(message,()=>{
        //     if(code && code!== 'ECONNABORTED'){
        //         $router.push({path:'/login'})
        //     }
        // })

        return false
    }
)
export default HTTP